package com.newgrand.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.newgrand.domain.model.CWBackModel;
import com.newgrand.domain.model.I8ReturnModel;
import com.newgrand.service.EnterpriseService;
import com.newgrand.utils.HttpClientUtil;
import com.newgrand.utils.JSONValid;
import com.newgrand.utils.TimeUtils;
import com.newgrand.utils.security.Md5Utils;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class EnterpriseImpl implements EnterpriseService {

    @Value("${cw.tokenUrl}")
    private String tokenUrl;
    @Value("${cw.addUrl}")
    private String addUrl;
    @Value("${cw.addBankUrl}")
    private String addBankUrl;
    @Value("${cw.delBankUrl}")
    private String delBankUrl;
    @Value("${cw.editUrl}")
    private String editUrl;
    @Value("${cw.editBankUrl}")
    private String editBankUrl;
    @Value("${cw.appID}")
    private String appID;
    @Value("${cw.appKEY}")
    private String appKEY;
    @Value("${cw.appSecret}")
    private String appSecret;
    private final JdbcTemplate jdbcTemplate;
    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public I8ReturnModel<String> sendSupply(String phid) {
        try {
            List<Map<String, Object>> dataList = jdbcTemplate.queryForList("select * from fg3_supplyfile_view where phid = ?", phid);
            if (dataList.isEmpty()) {
                return I8ReturnModel.success("无数据需要推送");
            }
            Map<String, Object> dataMap = dataList.get(0);
            if ("1".equals(dataMap.get("report_status"))) {
                dataMap.put("report_status", "-2");
                return sendSupplyEdit(dataMap, phid);
            }
            I8ReturnModel<String> returnModel = getToken();
            if (!returnModel.getIsOk()) {
                return I8ReturnModel.errorCode("401", "获取Token失败");
            }
            CWBackModel cwBackModel = JSONObject.parseObject(returnModel.getData(), CWBackModel.class);
            if (!"200".equals(cwBackModel.getCode())) {
                return I8ReturnModel.errorCode("401", cwBackModel.getMsg());
            }
            String sendUrl = addUrl;
            HashMap<String, Object> map = new HashMap<>();
            map.put("dataSourceId", "469912437211140096");
            map.put("modelId", "453711979262120484");
            map.put("data", dataMap);
            String body = JSON.toJSONString(map);
            logger.info("phid=" + phid + "，供应商推送报文：" + body);
            String tyStamp = String.valueOf(System.currentTimeMillis());
            String tySign = Md5Utils.hash(tyStamp + body + appSecret);
            Map<String, String> headers = new HashMap<>();
            headers.put("TYDTC_APP_TOKEN", cwBackModel.getData());
            sendUrl += "?tyStamp=" + tyStamp + "&tySign=" + tySign;
            returnModel = HttpClientUtil.sendPost(sendUrl, headers, body, "POST");
            logger.info("phid=" + phid + "，供应商推送返回结果：" + returnModel.getData());
            if (returnModel.getIsOk() && JSONValid.isJSON2(returnModel.getData())) {
                cwBackModel = JSONObject.parseObject(returnModel.getData(), CWBackModel.class);
                if ("200".equals(cwBackModel.getCode())) {
                    jdbcTemplate.update("update fg3_enterprise set user_gystb = '1' where phid = ?", phid);
                    jdbcTemplate.update("update fg3_supplyfile set user_tbzt = '1', user_tbsj = ?, user_tbjg = '新增推送成功' where ent_id = ?", TimeUtils.getDateStr(), phid);
                    return I8ReturnModel.success(cwBackModel.getMsg());
                }
                throw new RuntimeException(cwBackModel.getMsg());
            }
            throw new RuntimeException(returnModel.getMessage());
        } catch (Exception ex) {
            String msg = "推送失败:" + ex.getMessage();
            jdbcTemplate.update("update fg3_supplyfile set  user_tbsj = ?, user_tbjg = ? where ent_id = ?", TimeUtils.getDateStr(), msg, phid);
            return I8ReturnModel.errorCode("500", ex.getMessage());
        }
    }

    public I8ReturnModel<String> sendSupplyEdit(Map<String, Object> dataMap,String phid) {
        try {
            I8ReturnModel<String> returnModel = getToken();
            if (!returnModel.getIsOk()) {
                return I8ReturnModel.errorCode("401", "获取Token失败");
            }
            CWBackModel cwBackModel = JSONObject.parseObject(returnModel.getData(), CWBackModel.class);
            if (!"200".equals(cwBackModel.getCode())) {
                return I8ReturnModel.errorCode("401", cwBackModel.getMsg());
            }
            String sendUrl = editUrl;
            HashMap<String, Object> map = new HashMap<>();
            Map<String,Object> conditionsMap = new HashMap<>();
            Map<String,Object> conditionValuesMap = new HashMap<>();
            conditionsMap.put("internal_id","=");
            conditionValuesMap.put("internal_id",dataMap.get("internal_id"));
            map.put("values", dataMap);
            map.put("conditions", conditionsMap);
            map.put("conditionValues", conditionValuesMap);
            map.put("dataSourceId", "469912437211140096");
            map.put("modelId", "453711979262120484");

            String body = JSON.toJSONString(map);
            logger.info("phid=" + phid + "，供应商推送报文：" + body);
            String tyStamp = String.valueOf(System.currentTimeMillis());
            String tySign = Md5Utils.hash(tyStamp + body + appSecret);
            Map<String, String> headers = new HashMap<>();
            headers.put("TYDTC_APP_TOKEN", cwBackModel.getData());
            sendUrl += "?tyStamp=" + tyStamp + "&tySign=" + tySign;
            returnModel = HttpClientUtil.sendPost(sendUrl, headers, body, "POST");
            logger.info("phid=" + phid + "，供应商推送返回结果：" + returnModel.getData());
            if (returnModel.getIsOk() && JSONValid.isJSON2(returnModel.getData())) {
                cwBackModel = JSONObject.parseObject(returnModel.getData(), CWBackModel.class);
                if ("200".equals(cwBackModel.getCode())) {
                    jdbcTemplate.update("update fg3_enterprise set user_gystb = '1' where phid = ?", phid);
                    jdbcTemplate.update("update fg3_supplyfile set user_tbzt = '1', user_tbsj = ?, user_tbjg = '修改推送成功' where ent_id = ?", TimeUtils.getDateStr(), phid);
                    return sendSupplyBank(phid);
                }
                throw new RuntimeException(cwBackModel.getMsg());
            }
            throw new RuntimeException(returnModel.getMessage());
        } catch (Exception ex) {
            jdbcTemplate.update("update fg3_supplyfile set user_tbzt = '0', user_tbsj = ?, user_tbjg = '推送失败' where ent_id = ?", TimeUtils.getDateStr(), phid);
            return I8ReturnModel.errorCode("500", ex.getMessage());
        }
    }

    public I8ReturnModel<String> sendCustomEdit(Map<String, Object> dataMap,String phid) {
        try {
            I8ReturnModel<String> returnModel = getToken();
            if (!returnModel.getIsOk()) {
                return I8ReturnModel.errorCode("401", "获取Token失败");
            }
            CWBackModel cwBackModel = JSONObject.parseObject(returnModel.getData(), CWBackModel.class);
            if (!"200".equals(cwBackModel.getCode())) {
                return I8ReturnModel.errorCode("401", cwBackModel.getMsg());
            }
            String sendUrl = editUrl;
            HashMap<String, Object> map = new HashMap<>();
            Map<String,Object> conditionsMap = new HashMap<>();
            Map<String,Object> conditionValuesMap = new HashMap<>();
            conditionsMap.put("internal_id","=");
            conditionValuesMap.put("internal_id",dataMap.get("internal_id"));
            map.put("values", dataMap);
            map.put("conditions", conditionsMap);
            map.put("conditionValues", conditionValuesMap);
            map.put("dataSourceId", "469912437211140096");
            map.put("modelId", "453711979262120484");

            String body = JSON.toJSONString(map);
            logger.info("phid=" + phid + "，客户修改推送报文：" + body);
            String tyStamp = String.valueOf(System.currentTimeMillis());
            String tySign = Md5Utils.hash(tyStamp + body + appSecret);
            Map<String, String> headers = new HashMap<>();
            headers.put("TYDTC_APP_TOKEN", cwBackModel.getData());
            sendUrl += "?tyStamp=" + tyStamp + "&tySign=" + tySign;
            returnModel = HttpClientUtil.sendPost(sendUrl, headers, body, "POST");
            logger.info("phid=" + phid + "，客户修改推送返回结果：" + returnModel.getData());
            if (returnModel.getIsOk() && JSONValid.isJSON2(returnModel.getData())) {
                cwBackModel = JSONObject.parseObject(returnModel.getData(), CWBackModel.class);
                if ("200".equals(cwBackModel.getCode())) {
                    jdbcTemplate.update("update fg3_enterprise set user_gystb = '1' where phid = ?", phid);
                    jdbcTemplate.update("update fg3_customfile set user_tbzt = '1', user_tbsj = ?, user_tbjg = '修改推送成功' where ent_id = ?", TimeUtils.getDateStr(), phid);
                    return sendSupplyBank(phid);
                }
                throw new RuntimeException(cwBackModel.getMsg());
            }
            throw new RuntimeException(returnModel.getMessage());
        } catch (Exception ex) {
            jdbcTemplate.update("update fg3_customfile set  user_tbsj = ?, user_tbjg = '推送失败' where ent_id = ?", TimeUtils.getDateStr(), phid);
            return I8ReturnModel.errorCode("500", ex.getMessage());
        }
    }

    @Override
    public I8ReturnModel<String> sendSupplyBank(String phid) {
        try {
            List<Map<String, Object>> dataList = jdbcTemplate.queryForList("select *from fg3_supplyfile_bank_view where supply_id = ?", phid);
            if (dataList.isEmpty()) {
                return I8ReturnModel.success("无数据需要推送");
            }
            I8ReturnModel<String> returnModel = getToken();
            if (!returnModel.getIsOk()) {
                return I8ReturnModel.errorCode("401", "获取Token失败");
            }
            CWBackModel cwBackModel = JSONObject.parseObject(returnModel.getData(), CWBackModel.class);
            if (!"200".equals(cwBackModel.getCode())) {
                return I8ReturnModel.errorCode("401", cwBackModel.getMsg());
            }

            for (Map<String, Object> dataMap : dataList) {
                String sendUrl = addBankUrl;
                if ("1".equals(dataMap.get("report_status"))) {
                    dataMap.put("report_status", "-2");
                    sendUrl = editUrl;
                }

                HashMap<String, Object> map = new HashMap<>();
                map.put("dataSourceId", "469912437211140096");
                map.put("modelId", "453711979262120484");
                map.put("data", dataMap);
                String body = JSON.toJSONString(map);
                logger.info("phid=" + phid + "，供应商银行账户推送报文：" + body);
                String tyStamp = String.valueOf(System.currentTimeMillis());
                String tySign = Md5Utils.hash(tyStamp + body + appSecret);
                Map<String, String> headers = new HashMap<>();
                headers.put("TYDTC_APP_TOKEN", cwBackModel.getData());
                sendUrl += "?tyStamp=" + tyStamp + "&tySign=" + tySign;
                returnModel = HttpClientUtil.sendPost(sendUrl, headers, body, "POST");
                logger.info("phid=" + phid + "，供应商银行账户推送返回结果：" + returnModel.getData());
                if (returnModel.getIsOk() && JSONValid.isJSON2(returnModel.getData())) {
                    cwBackModel = JSONObject.parseObject(returnModel.getData(), CWBackModel.class);
                    if ("200".equals(cwBackModel.getCode())) {
//                        jdbcTemplate.update("WITH SupplyFileInfo AS (\n" +
//                                "  SELECT ent_id, org_id\n" +
//                                "  FROM fg3_supplyfile\n" +
//                                "  WHERE phid = ?\n" +
//                                ")\n" +
//                                "UPDATE s\n" +
//                                "SET s.user_tbzt = '1'\n" +
//                                "FROM fg3_supplysettleinfo AS s\n" +
//                                "JOIN SupplyFileInfo AS c ON s.ent_id = c.ent_id AND s.org_id = c.org_id", phid);
                        jdbcTemplate.update("update fg3_supplysettleinfo set user_tbzt = '1' where phid = ?" ,dataMap.get("phid"));
                        return I8ReturnModel.success(cwBackModel.getMsg());
                    }
                    throw new RuntimeException(cwBackModel.getMsg());
                }
                throw new RuntimeException(returnModel.getMessage());
            }
            return I8ReturnModel.success();
        } catch (Exception ex) {
            return I8ReturnModel.errorCode("500", ex.getMessage());
        }
    }

    @Override
    public I8ReturnModel<String> sendSupplyBankBatch() {
        List<Map<String, Object>> dataList = jdbcTemplate.queryForList("select * from fg3_supplyfile_view where report_status = '1' ");
        for(Map<String, Object> item : dataList){
            sendSupplyBank(String.valueOf(item.get("phid")));
        }
        return I8ReturnModel.success();
    }

    @Override
    public I8ReturnModel<String> sendCustom(String phid) {
        try {
            List<Map<String, Object>> dataList = jdbcTemplate.queryForList("select * from fg3_customfile_view where phid = ?", phid);
            if (dataList.isEmpty()) {
                return I8ReturnModel.success("无数据需要推送");
            }
            I8ReturnModel<String> returnModel = getToken();
            if (!returnModel.getIsOk()) {
                return I8ReturnModel.errorCode("401", "获取Token失败");
            }
            CWBackModel cwBackModel = JSONObject.parseObject(returnModel.getData(), CWBackModel.class);
            if (!"200".equals(cwBackModel.getCode())) {
                return I8ReturnModel.errorCode("401", cwBackModel.getMsg());
            }

            String sendUrl = addUrl;
            Map<String, Object> dataMap = dataList.get(0);
            if ("1".equals(dataMap.get("report_status"))) {
                return sendCustomEdit(dataMap, phid);
            }

            HashMap<String, Object> map = new HashMap<>();
            map.put("dataSourceId", "469912437211140096");
            map.put("modelId", "453711979262120484");
            map.put("data", dataMap);
            String body = JSON.toJSONString(map);
            logger.info("phid=" + phid + "，客户推送报文：" + body);
            String tyStamp = String.valueOf(System.currentTimeMillis());
            String tySign = Md5Utils.hash(tyStamp + body + appSecret);
            Map<String, String> headers = new HashMap<>();
            headers.put("TYDTC_APP_TOKEN", cwBackModel.getData());
            sendUrl += "?tyStamp=" + tyStamp + "&tySign=" + tySign;
            returnModel = HttpClientUtil.sendPost(sendUrl, headers, body, "POST");
            logger.info("phid=" + phid + "，客户推送返回结果：" + returnModel.getData());
            if (returnModel.getIsOk() && JSONValid.isJSON2(returnModel.getData())) {
                cwBackModel = JSONObject.parseObject(returnModel.getData(), CWBackModel.class);
                if ("200".equals(cwBackModel.getCode())) {
                    jdbcTemplate.update("update fg3_enterprise set user_gystb = '1' where phid = ? ", phid);
                    jdbcTemplate.update("update fg3_customfile set user_tbzt = '1', user_tbsj = ?, user_tbjg = '新增推送成功' where ent_id = ?", TimeUtils.getDateStr(), phid);
                    sendCustomBank(phid);
                    return I8ReturnModel.success(cwBackModel.getMsg());
                }
                throw new RuntimeException(cwBackModel.getMsg());
            }
            throw new RuntimeException(returnModel.getMessage());
        } catch (Exception ex) {
            String msg = "推送失败:" + ex.getMessage();
            jdbcTemplate.update("update fg3_customfile set  user_tbsj = ?, user_tbjg = ? where ent_id = ?", TimeUtils.getDateStr(), msg, phid);
            return I8ReturnModel.errorCode("500", ex.getMessage());
        }
    }

    @Override
    public I8ReturnModel<String> sendCustomBank(String phid) {
        try {
            List<Map<String, Object>> dataList = jdbcTemplate.queryForList("select * from fg3_customfile_bank_view where custom_id = ?", phid);
            if (dataList.isEmpty()) {
                return I8ReturnModel.success("无数据需要推送");
            }
            I8ReturnModel<String> returnModel = getToken();
            if (!returnModel.getIsOk()) {
                return I8ReturnModel.errorCode("401", "获取Token失败");
            }
            CWBackModel cwBackModel = JSONObject.parseObject(returnModel.getData(), CWBackModel.class);
            if (!"200".equals(cwBackModel.getCode())) {
                return I8ReturnModel.errorCode("401", cwBackModel.getMsg());
            }

            for (Map<String, Object> dataMap : dataList) {
                String sendUrl = addBankUrl;
                HashMap<String, Object> map = new HashMap<>();
                map.put("dataSourceId", "469912437211140096");
                map.put("modelId", "453711979262120484");

                if ("1".equals(dataMap.get("report_status")) || "2".equals(dataMap.get("report_status"))) {
                    dataMap.put("report_status", "-2");
                    sendUrl = editBankUrl;
                    Map<String,Object> conditionsMap = new HashMap<>();
                    Map<String,Object> conditionValuesMap = new HashMap<>();
                    conditionsMap.put("internal_id","=");
                    conditionValuesMap.put("internal_id",dataMap.get("internal_id"));
                    map.put("values", dataMap);
                    map.put("conditions", conditionsMap);
                    map.put("conditionValues", conditionValuesMap);
                    map.put("dataSourceId", "469912437211140096");
                    map.put("modelId", "453711979262120484");
                }else{
                    dataMap.put("report_status", "-1");
                    map.put("data", dataMap);
                }

                String body = JSON.toJSONString(map);
                logger.info("phid=" + phid + "，客户银行信息推送报文：" + body);
                String tyStamp = String.valueOf(System.currentTimeMillis());
                String tySign = Md5Utils.hash(tyStamp + body + appSecret);
                Map<String, String> headers = new HashMap<>();
                headers.put("TYDTC_APP_TOKEN", cwBackModel.getData());
                sendUrl += "?tyStamp=" + tyStamp + "&tySign=" + tySign;
                returnModel = HttpClientUtil.sendPost(sendUrl, headers, body, "POST");
                logger.info("phid=" + phid + "，客户银行信息推送返回结果：" + returnModel.getData());
                if (returnModel.getIsOk() && JSONValid.isJSON2(returnModel.getData())) {
                    cwBackModel = JSONObject.parseObject(returnModel.getData(), CWBackModel.class);
                    if ("200".equals(cwBackModel.getCode())) {
//                        jdbcTemplate.update("WITH CustomFileInfo AS (\n" +
//                                "  SELECT ent_id, org_id\n" +
//                                "  FROM fg3_customfile\n" +
//                                "  WHERE phid = ?\n" +
//                                ")\n" +
//                                "UPDATE s\n" +
//                                "SET s.user_tbzt = '1'\n" +
//                                "FROM fg3_supplysettleinfo AS s\n" +
//                                "JOIN CustomFileInfo AS c ON s.ent_id = c.ent_id AND s.org_id = c.org_id;", phid);
                        jdbcTemplate.update("update fg3_customsettleinfo set user_tbzt = '1' where phid = ?",dataMap.get("phid"));
                        return I8ReturnModel.success(cwBackModel.getMsg());
                    }
                    throw new RuntimeException(cwBackModel.getMsg());
                }
                throw new RuntimeException(returnModel.getMessage());
            }
            return I8ReturnModel.success();
        } catch (Exception ex) {
            return I8ReturnModel.errorCode("500", ex.getMessage());
        }
    }

    @Override
    public I8ReturnModel<String> sendCustomBankDelete(String phid) {
        try {
            List<Map<String, Object>> dataList = jdbcTemplate.queryForList("select * from fg3_customfile_bank_view where custom_id = ?", phid);
            if (dataList.isEmpty()) {
                return I8ReturnModel.success("无数据需要推送");
            }
            I8ReturnModel<String> returnModel = getToken();
            if (!returnModel.getIsOk()) {
                return I8ReturnModel.errorCode("401", "获取Token失败");
            }
            CWBackModel cwBackModel = JSONObject.parseObject(returnModel.getData(), CWBackModel.class);
            if (!"200".equals(cwBackModel.getCode())) {
                return I8ReturnModel.errorCode("401", cwBackModel.getMsg());
            }

            for (Map<String, Object> dataMap : dataList) {
                String sendUrl = addBankUrl;
                HashMap<String, Object> map = new HashMap<>();
                map.put("dataSourceId", "469912437211140096");
                map.put("modelId", "453711979262120484");
                dataMap.put("report_status", "-3");
                sendUrl = delBankUrl;
                Map<String,Object> conditionsMap = new HashMap<>();
                Map<String,Object> conditionValuesMap = new HashMap<>();
                conditionsMap.put("internal_id","=");
                conditionValuesMap.put("internal_id",dataMap.get("internal_id"));
                map.put("conditions", conditionsMap);
                map.put("conditionValues", conditionValuesMap);

                String body = JSON.toJSONString(map);
                logger.info("phid=" + phid + "，客户银行信息删除推送报文：" + body);
                String tyStamp = String.valueOf(System.currentTimeMillis());
                String tySign = Md5Utils.hash(tyStamp + body + appSecret);
                Map<String, String> headers = new HashMap<>();
                headers.put("TYDTC_APP_TOKEN", cwBackModel.getData());
                sendUrl += "?tyStamp=" + tyStamp + "&tySign=" + tySign;
                returnModel = HttpClientUtil.sendPost(sendUrl, headers, body, "POST");
                logger.info("phid=" + phid + "，客户银行信息删除推送返回结果：" + returnModel.getData());
                if (returnModel.getIsOk() && JSONValid.isJSON2(returnModel.getData())) {
                    cwBackModel = JSONObject.parseObject(returnModel.getData(), CWBackModel.class);
                    if ("200".equals(cwBackModel.getCode())) {
                        jdbcTemplate.update("update fg3_customsettleinfo set user_tbzt = '3' where phid = ?",dataMap.get("phid"));
                        return I8ReturnModel.success(cwBackModel.getMsg());
                    }
                    throw new RuntimeException(cwBackModel.getMsg());
                }
                throw new RuntimeException(returnModel.getMessage());
            }
            return I8ReturnModel.success();
        } catch (Exception ex) {
            return I8ReturnModel.errorCode("500", ex.getMessage());
        }
    }

    @Async("asyncServiceExecutor")
    @Override
    public I8ReturnModel<String> sendSupplyBatch() {
        List<Map<String, Object>> dataList = jdbcTemplate.queryForList("select * from fg3_supplyfile_view");
        for (Map<String, Object> item : dataList) {
            sendSupply(String.valueOf(item.get("phid")));
        }
        return I8ReturnModel.success();
    }

    @Async("asyncServiceExecutor")
    @Override
    public I8ReturnModel<String> sendCustomBatch() {
        List<Map<String, Object>> dataList = jdbcTemplate.queryForList("select * from fg3_customfile_view");
        for (Map<String, Object> item : dataList) {
            sendCustom(String.valueOf(item.get("phid")));
        }
        return I8ReturnModel.success();
    }

    @Override
    public I8ReturnModel<String> sendCustomBankBatch() {
        List<Map<String, Object>> dataList = jdbcTemplate.queryForList("select * from fg3_customfile_view where report_status = '1' ");
        for (Map<String, Object> item : dataList) {
            sendCustomBank(String.valueOf(item.get("phid")));
        }
        return I8ReturnModel.success();
    }

    public I8ReturnModel<String> getToken() {
        Map<String, String> map = new HashMap<>();
        map.put("TYDTC_APP_ID", appID);
        map.put("TYDTC_APP_KEY", appKEY);
        return HttpClientUtil.sendPost(tokenUrl, map, "", "GET");
    }
}
